<template>
	<Layout>
		<Spin fix v-if="isSpin">
		    <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
		    <div>正在生成处罚通知单，请稍后</div>
		</Spin>
		<Form ref="form1" :model="form1" :label-width="120">
			<Row class="query-form" style="padding-top: 10px">
				<Col span="8">
				   <FormItem label="被考核单位：" prop="assessedOrgId">
				    <cascaderDom class="query-form-el" style="padding-top: 4px; width: 100%;" ref="carOrg"
				    	@setOrgInfo="setOrgId" @setOrgName="setOrgName"
				    	:currentOrgId="form1.assessedOrgId" :currentOrgName="form1.orgName"
				    	:orgTree="true"></cascaderDom>
				  </FormItem>
				</Col>
				<Col span="8">
				<FormItem label="年份：" prop="year">
					<Input class="query-form-el" type="text" v-model="form1.year" clearable></Input>
				</FormItem>
				</Col>
				<Col span="8">
				<Button @click="reset" class="ivu-btn-reset">重置</Button>
				<Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
				</Col>
			</Row>
			<Row class="query-form">
				<Col span="24">
					<Button type="primary" class="ivu-btn-add"   icon="md-cloud-download" :loading="buttonLoading" @click="exportFormSubmit">导出</Button>
				</Col>
			</Row>
		</Form>
		<Table ref='table' :loading="loading" size="small" :height="tableHeight" no-data-text="没有查询到相关数据!"
			@on-selection-change='getSelectRows' border :columns="columns1" :row-class-name="rowClassName" :data="dataTable" >
		</Table>
		<Row style="margin-right:10px;">
			<Col span="24">
			<Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
				@on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
				show-elevator />
			</Col>
		</Row>

		<Modal title="处罚详情" :transfer=false v-model="model2" :width=800>
			<Row>
				<Col span="24">
				<Form :model="showdata" :label-width="160">
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label="被考核单位:">
							{{showdata.assessedOrgName}}
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label="年份:">
							{{showdata.year}}
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg detail-background-clor">
						<Col span="11">
						<FormItem label="季度:">
							{{showdata.quarter}}季度
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label="车牌号:">
							{{showdata.plateNumber}}
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label="罚款金额(元):">
							{{showdata.penalty}}
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label="扣分:">
							{{showdata.score}}
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg detail-background-clor">
						<Col span="11">
						<FormItem label="检查时间:" >
							{{showdata.inspectionDate}}
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label="检查人:">
							{{showdata.inspectionName}}
						</FormItem>
						</Col>
					</Row>
				</Form>
				</Col>
			</Row>
			<div slot="footer">
				<Button class='ivu-btn-save' @click="model2=false">关闭</Button>
			</div>
		</Modal>
	</Layout>
</template>

<script>
	import {
		Api
	} from '../../../../api/index.js'
	import {
		sessionStorage
	} from '../../../../common/cacheUtils.js';
	import cascaderDom from "../../../../components/cascader-dom.vue"

	export default {
		name: "violation",
		components: {
			cascaderDom
		},
		data() {
			return {
				isSpin: false,
				carInfo: {},
				switchFlag: false,
				form1: {},
				pageSizeArray: [10, 20, 50],
				pagedata: {
					total: 0,
					pageSize: 10,
					currentPage: 1,
				},
				dataTable: [],
				columns1: [{
						title: "序号",
						width: 80,
						align: "center",
						fixed: 'left',
						render: (h, params) => {
							return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata
								.pageSize + 1);
						}
					},
					{
						title: '被考核单位',
						minWidth: 200,
						align: 'center',
						fixed: 'left',
						key: 'assessedOrgName',
					},
					{
						title: '年份',
						minWidth: 100,
						align: 'center',
						fixed: 'left',
						key: 'year',
					},
					{
						title: '季度',
						minWidth: 120,
						align: 'center',
						key: 'quarter',
						render: (h, params) => {
							return h('span', params.row.quarter+"季度");
						}
					},
					{
						title: '车牌号',
						minWidth: 150,
						align: 'center',
						key: 'plateNumber',
					},
					{
						title: '罚款金额(元)',
						minWidth: 150,
						align: 'center',
						key: 'penalty',
					},
					{
						title: '扣分',
						minWidth: 80,
						align: 'center',
						key: 'score',
					},
					{
						title: '检查时间',
						minWidth: 150,
						align: 'center',
						key: 'inspectionDate',
						render: (h, params) => {
							return h('div', [
								(this.formatDate(new Date(params.row.inspectionDate), 'yyyy-MM-dd'))
							]);
						}
					},
					{
						title: '检查人',
						minWidth: 100,
						align: 'center',
						key: 'inspectionName',
					},
					{
						title: '操作',
						key: 'action',
						fixed: 'right',
						width: 200,
						align: 'center',
						render: (h, params) => {
							return h('div', [
								h('A', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										fontSize: '14px',
									},
									on: {
										click: () => {
											this.showData(params, 1);
										}
									}
								}, '详情'), 
								h('Divider', {
									props: {
										type: 'vertical',
									}
								}, ''),
								h('A', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										fontSize: '14px',
									},
									on: {
										click: () => {
											this.downLoad(params);
										}
									}
								}, '下载处罚单')
							]);
						}
					},
				],
				add: false,
				model1: false,
				buttonLoading: false,
				model2: false,
				showdata: {},
				loading: false,
				tableHeight: 10,
				currentOrgId: '',
				currentOrgName: '',
			}
		},
		async mounted() {
			this.form1.type = this.$route.query.id
			this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
			this.query();
		},
		methods: {
			setOrgId(data) {
				this.form1.assessedOrgId = data[data.length - 1];
			},
			setOrgName(data) {
				this.form1.orgName = data;
			},

			pageChange(pageNum) {
				this.pagedata.currentPage = pageNum;
				this.query();
			},
			pageSizeChange(pageSize) {
				this.pagedata.pageSize = pageSize;
				this.query();
			},
			handleCancel() {
				this.form1={};
				this.model1 = false;
			},
			switchQuery(flag) {
				this.switchFlag = flag;
				if (!this.switchFlag) {
					this.tableHeight = this.tableHeight + 44;
				} else {
					this.tableHeight = this.tableHeight - 44;
				}
			},
			reset() {
				this.form1 = {}
				this.query()
			},
			query() {
				this.loading = true;
				if(!this.form1.yearDate) {
				    this.form1.yearDate = new Date();
				}
				if(this.form1.yearDate) {
				  this.form1.year = this.form1.yearDate.getFullYear();
				}
				this.form1.type = this.$route.query.id
				this.form1.orgId = sessionStorage('userId').getObject('userId').companyId;
				let data = {
					startPage: this.pagedata.currentPage,
					size: this.pagedata.pageSize,
					conditions: this.form1
				};
				let url = Api.queryEqTrafficPenalty;
				this.$http.post(url,data).then((res) => {
					if (res.data.status === 201) {
					    this.$Message.error(res.data.msg);
						this.loading = false;
					}
					this.dataTable = res.data.data.data;
					this.pagedata.total = res.data.data.totalSize;
					this.loading = false;
				}).catch(e => {
					this.$Message.error("数据获取失败")
					this.loading = false;
				})
			},
			exportFormSubmit() {
				this.buttonLoading=true
				let orgId = sessionStorage('userId').getObject('userId').companyId
				let data = {
				    orgId:orgId,
					type:this.$route.query.id
				};
				data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
				this.$http.get(Api.exportPenalty, {
				    params:data,
				    responseType: 'blob'      //告诉服务器我们需要的响应格式
				}).then((res) => {
				    const aLink = document.createElement("a");
				    let blob = new Blob([res.data], {
				        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
				    });
				    aLink.href = URL.createObjectURL(blob)
				    aLink.download = "交通处罚记录("+ this.formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
				    aLink.click()
				    document.body.appendChild(aLink)
				    this.buttonLoading=false
				})
			},
			showData(data, flag) {
				if (flag == 1) {
					//查看页面
					this.showdata = data.row;
					this.showdata.inspectionDate = this.formatDate(new Date(this.showdata.inspectionDate), 'yyyy-MM-dd');
					this.model2 = true;
				}
			},
			formatDate(date, fmt) {
				if (/(y+)/.test(fmt)) {
					fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				let o = {
					'M+': date.getMonth() + 1,
					'd+': date.getDate(),
					'h+': date.getHours(),
					'm+': date.getMinutes(),
					's+': date.getSeconds()
				};
				for (let k in o) {
					if (new RegExp(`(${k})`).test(fmt)) {
						let str = o[k] + '';
						fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
					}
				}
				return fmt;
			},
			padLeftZero(str) {
				return ('00' + str).substr(str.length);
			},
			rowClassName(row,index){
				if(row.score>5){
					return 'table-row-red';
				}
				if(row.penaltyType==2){
					return 'table-row-yellow';
				}
			},
			downLoad(data){
				this.isSpin = true;
				this.$http.get(Api.downloadPenalty,{
				    params:{
						id:data.row.id,
					},
				    responseType: 'arraybuffer'
				}).then((res) => {
				    const aLink = document.createElement("a");
				    let blob = new Blob([res.data], {
				        type: "application/msword"
				    })
				    aLink.href = URL.createObjectURL(blob);
				    aLink.download = "交通违章处罚通知单.doc" //标题
				    aLink.click();
				    document.body.appendChild(aLink);
				    this.isSpin = false;
				}).catch(e => {
				    this.$Message.error("数据获取失败");
				    this.isSpin = false;
				})
			},
			padLeftZero(str) {
				return ('00' + str).substr(str.length);
			},
			getSelectRows(rows) {
				this.deleteRows = rows;
			},
		},
		watch: {
			"model1": function(qw, er) {
				if (qw && this.model1) {
					setTimeout(() => {
						this.$refs.carOrg.setCurrentOrg();
					}, 100)
				} else {
					this.$refs.carOrg.setCurrentOrg();
				}
			},
		},
	}
</script>

<style lang='css'>
	@import '../../../../index.css';
	.ivu-table-tbody .table-row-red td{
	    background-color: #fedede !important;
	}
	.ivu-table-tbody .table-row-yellow td{
	    background-color: #fff2cc !important;
	}
</style>
